package ice.webapp.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cube.io.StreamUtil;
import cube.utils.BeanUtil;

/**
 * BaseAction
 */
public abstract class BaseAction {

    /**
     * 请求列表
     */
    private Map<String, String> requestMap = new HashMap<String, String>();

    /**
     * Http请求
     */
    private HttpServletRequest request;

    /**
     * Http应答
     */
    private HttpServletResponse response;

    /**
     * 对请求和Action方法进行绑定
     */
    protected void bind(String requestUri, String method) {
        requestMap.put(requestUri, method);
    }

    /**
     * 获取请求列表
     */
    public Map<String, String> getRequestUrlMap() {
        return Collections.unmodifiableMap(requestMap);
    }

    /**
     * 调用Action方法
     */
    public void invokeMethod(String requestUri) {
        String method = requestMap.get(requestUri);
        BeanUtil.invoke(this, method);
    }

    /**
     * @return the request
     */
    public HttpServletRequest getRequest() {
        return request;
    }

    /**
     * @param request the request to set
     */
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * @return the response
     */
    public HttpServletResponse getResponse() {
        return response;
    }

    /**
     * @param response the response to set
     */
    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    /**
     * 获取json参数
     */
    protected String getJsonParam() {
        String jsonData = request.getParameter("json");
        if (jsonData == null || "".equals(jsonData)) {
            try {
                InputStream is = request.getInputStream();
                jsonData = StreamUtil.read(is, "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonData;
    }

    /**
     * 发送应答结果
     */
    protected void response(String result) {
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(result.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StreamUtil.close(os);
        }
    }
}
